#include "dut/Shader.h"

HRESULT Dut::Shader::Create(ID3D11Device* device, const std::wstring& vpath, const std::wstring& fpath, const D3D11_INPUT_ELEMENT_DESC* desc, int numDesc)
{
    std::wstring vertcsoPath = vpath + L".cso";
    std::wstring fragcsoPath = fpath + L".cso";

    DeleteFile(vertcsoPath.c_str());
    DeleteFile(fragcsoPath.c_str());


    ComPtr<ID3DBlob> blob;

    HR(CreateShaderFromFile(vertcsoPath.c_str(), vpath.c_str(), "VS", "vs_5_0", blob.ReleaseAndGetAddressOf()));
    HR(device->CreateVertexShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, m_pVertexShader.GetAddressOf()));
   
    HR(device->CreateInputLayout(desc, numDesc,
        blob->GetBufferPointer(), blob->GetBufferSize(), m_pVertexLayout.GetAddressOf()));


    HR(CreateShaderFromFile(fragcsoPath.c_str(), fpath.c_str(), "PS", "ps_5_0", blob.ReleaseAndGetAddressOf()));
    HR(device->CreatePixelShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, m_pPixelShader.GetAddressOf()));

    return S_OK;
}

void Dut::Shader::Use(ID3D11DeviceContext* context)
{
    HRESULT hr;


    context->IASetInputLayout(m_pVertexLayout.Get());
    context->VSSetShader(m_pVertexShader.Get(), nullptr, 0);
    context->PSSetShader(m_pPixelShader.Get(), nullptr, 0);

}

HRESULT Dut::Shader::CreateShaderFromFile(const WCHAR* csoFileNameInOut, const WCHAR* hlslFileName, LPCSTR entryPoint, LPCSTR shaderModel, ID3DBlob** ppBlobOut)
{
    HRESULT hr = S_OK;

    if (csoFileNameInOut && D3DReadFileToBlob(csoFileNameInOut, ppBlobOut) == S_OK)
    {
        return hr;
    }
    else
    {
        DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;
#ifdef _DEBUG
        dwShaderFlags |= D3DCOMPILE_DEBUG;

        dwShaderFlags |= D3DCOMPILE_SKIP_OPTIMIZATION;
#endif
        ID3DBlob* errorBlob = nullptr;
        hr = D3DCompileFromFile(hlslFileName, nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, entryPoint, shaderModel,
            dwShaderFlags, 0, ppBlobOut, &errorBlob);
        if (FAILED(hr))
        {
            if (errorBlob != nullptr)
            {
                OutputDebugStringA(reinterpret_cast<const char*>(errorBlob->GetBufferPointer()));
            }
            SAFE_RELEASE(errorBlob);
            return hr;
        }

        if (csoFileNameInOut)
        {
            return D3DWriteBlobToFile(*ppBlobOut, csoFileNameInOut, FALSE);
        }
    }

    return hr;
}



